/**
 * @file swei_cmd.c
 * @brief 
 * @author henry.cai (henry.cai@queclink.com)
 * @version 1.0
 * @date 2024-09-09
 * 
 * @copyright Copyright (C) 2019 Queclink Wireless Solutions (ShenZhen) Co., Ltd. All Rights Reserved.
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2024-09-09 <td>1.0     <td>henry.cai     <td>内容
 * </table>
 */
#include "global.h"
#include "include/port/swei_log.h"
#include "service/include/swei_ota.h"

#include "include/swei_cmd.h"

static pf_cmd_callback_func gs_cbfun[DOWN_LINK_CMD_NUM_MAX]; // 回调函数table



/**
 * @description: 注册处理指令回调函数
 * @param {DOWN_LINK_CMD_ENUM} cmd_id
 * @param {pf_cmd_callback_func} cb_func
 * @return {*}
 * @Date: 2023-10-30 09:35:15
 * @modification: 注意，该函数里不要加sleep延时！！
 */
void swei_downlink_cmd_register(DOWN_LINK_CMD_ENUM cmd_id, pf_cmd_callback_func cb_func)
{
    if (cmd_id < DOWN_LINK_CMD_ACTIVATE || cmd_id >= DOWN_LINK_CMD_NUM_MAX)
    {
        log_e("reg cbfunc fail!![id %d]", cmd_id);
        return;
    }
    if (cb_func == NULL)
    {
        log_e("reg cbfunc fail!![cbfun is null]");
        return;
    }

    if (gs_cbfun[cmd_id] != NULL) 
    {
        log_w("cbfun for cmdid=0x%x already exists, will be override.", cmd_id); // 若重复设置，则打印一个告警
    }
    gs_cbfun[cmd_id] = cb_func;

    return;
}



/**
 * @brief 下行数据处理入口函数
 * @param  cmd_id           My Param doc
 * @param  cmd_opcode       My Param doc
 * @param  p_data           My Param doc
 * @param  data_len         My Param doc
 * @return DLCMD_RET_TYPE_ENUM 
 */
DLCMD_RET_TYPE_ENUM swei_downlink_cmd_handler(DOWN_LINK_CMD_ENUM cmd_id, uint16_t cmd_opcode, const uint8_t *p_data, uint32_t data_len)
{
    if (is_tbox_ota()) {
        log_i("device is in ota, fail to activate\r\n");
        return DLCMD_IS_OTA;
    }

    if (gs_cbfun[cmd_id] != NULL)
    {
        DLCMD_RET_TYPE_ENUM cb_ret = (*gs_cbfun[cmd_id])(cmd_id, cmd_opcode, p_data, data_len);

        return cb_ret;
    }

    return DLCMD_NOT_SUPPORT;
}


#include "include/swei_findbike.h"
#include "include/swei_reboot.h"
#include "include/swei_imme_loc.h"

/**
 * @brief 设备下行指令功能初始化
 */
void swei_downlink_cmd_init(void)
{
    /* 1. 寻车功能初始化 */
    swei_findbike_init();

    /* 2. 重启功能初始化 */
    swei_reboot_init();

    /* 3. 立即定位功能初始化 */
    swei_imme_location_init();
}